package com.yjf.ljr.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.util.EncodingUtils;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yjf.ljr.R;
import com.yjf.ljr.adapter.CommonAdapter;
import com.yjf.ljr.adapter.CommonAdapter.HandleCallBack;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.dataclass.EasyDataClass;
import com.yjf.ljr.dataclass.ImageUploadDataClass;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;
import com.yjf.ljr.util.AppUtil;
import com.yjf.ljr.util.ImageLoader;
import com.yjf.ljr.util.ImageUtils;
import com.yjf.ljr.util.PicLoad;
import com.yjf.ljr.util.AppUtil.HandlerItemCallBack;
import com.yjf.ljr.view.PhotoDialog;

public class IdentityVerifyActivity extends IjActivity implements View.OnClickListener {

	public static final int ID_PHOTO_FRONT_PICK = 1;
	public static final int ID_PHOTO_BACK_PICK = 2;
	public static final String IMAGE_UNSPECIFIED = "image/*";

	public static final int IDENTITY_QUICK_TYPE = 4;
	public static final int IDENTITY_HOLDING = 5;
	public static final int IDENTITY_NORMAL = 6;

	@ID("identity_name_verify")
	private EditText identityNameVerify;
	@ID("identity_credential_verify")
	private EditText identityCredentialVerify;
	@ID("identity_ID_expiration_time_verify")
	private TextView identityIDExpirationTimeVerify;
	@ID("long_time")
	private CheckBox longTime;
	@ID("shoot_ID")
	private Button shootID;
	@ID("identity_ID_photo_front")
	private ImageButton photoIDFront;
	@ID("identity_ID_photo_back")
	private ImageButton photoIDBack;
	@ID("tvIdentity")
	private TextView mTvIdentity;
	@ID("normal_container")
	private LinearLayout normalContainer;
	@ID("identityTip")
	private TextView identityTip;

	@ID("identity_ID_photo_front_tip")
	private TextView identityIDPhotoFrontTip;

	private DatePickerDialog datePickerDialog;

	public static String mFilePath = ""; // 图片存储路径，与ImageLoader一致

	private boolean isIDFrontPhotoUpload = false;
	private boolean isIDBackPhotoUpload = false;

	public static final String mIDFrontFileName = "frontIDtemp.jpg";
	public static final String mIDBackFileName = "backIDtemp.jpg";

	private String token;

	private String frontImageServerPath = "";
	private String backImageServerPath = "";

	private PhotoDialog photoDialog;

	private boolean isUpdate = false;
	private int currentType;

	private String[] allTypes;
	private String[] noneQuickTypes;
	private String quickType;
	private String normalType;
	private String holdType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_identity_verify);
		initControls();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	private void initControls() {
		setLeftBtnClick();
		setTitleStr(getString(R.string.identity_verify));
		token = getIntent().getStringExtra("token");
		if (TextUtils.isEmpty(token)) {
			token = "";
		}
		isUpdate = getIntent().getBooleanExtra("isUpdate", false);
		currentType = IDENTITY_QUICK_TYPE;

		if (isUpdate) {
			identityNameVerify.setEnabled(false);
			identityCredentialVerify.setEnabled(false);
			mTvIdentity.setEnabled(true);
			String realName = getIntent().getStringExtra("name");
			String realCertNo = getIntent().getStringExtra("realCertNo");
			if (!TextUtils.isEmpty(realName)) {
				identityNameVerify.setText(realName);
			}
			if (!TextUtils.isEmpty(realCertNo)) {
				identityCredentialVerify.setText(realCertNo);
			}
			currentType = IDENTITY_NORMAL;
			normalContainer.setVisibility(View.VISIBLE);
			mTvIdentity.setText(R.string.identity_level_normal_verify);
			identityTip.setText(R.string.identity_normal_tip);
		} else {
			identityNameVerify.setEnabled(true);
			mTvIdentity.setEnabled(true);
			identityCredentialVerify.setEnabled(true);
			normalContainer.setVisibility(View.GONE);
		}

		allTypes = getResources().getStringArray(R.array.all_identity_level_type);
		noneQuickTypes = getResources().getStringArray(R.array.none_quick_identity_level_type);
		quickType = getString(R.string.identity_level_quick_verify);
		normalType = getString(R.string.identity_level_normal_verify);
		holdType = getString(R.string.identity_level_hold_verify);

		identityIDExpirationTimeVerify.setOnClickListener(this);
		photoIDFront.setOnClickListener(this);
		photoIDBack.setOnClickListener(this);
		shootID.setOnClickListener(this);
		mTvIdentity.setOnClickListener(this);

		longTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (isChecked) {
					identityIDExpirationTimeVerify.setText("");
				}
			}
		});

		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
			mFilePath = CommonData.IMAMGE_DIR_SD + "/";
		} else {
			mFilePath = CommonData.IMAMGE_DIR_RAM + "/";
		}

		File file = new File(mFilePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		selectLevelType(mTvIdentity.getText().toString());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 选择身份证时间
		case R.id.identity_ID_expiration_time_verify:
			if (!longTime.isChecked()) {
				Calendar now = Calendar.getInstance();

				Date date = new Date();
				// 创建一个Date实例
				now.setTime(date);
				// 设置日历的时间，把一个新建Date实例myDate传入
				int year = now.get(Calendar.YEAR);
				int month = now.get(Calendar.MONTH);
				int day = now.get(Calendar.DAY_OF_MONTH);

				if (datePickerDialog == null) {
					datePickerDialog = new DatePickerDialog(IdentityVerifyActivity.this, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
							updateIDExpires(year, monthOfYear, dayOfMonth);
						}
					}, year, month, day);
				}

				if (!datePickerDialog.isShowing()) {
					datePickerDialog.show();
				}
			}
			break;
		// 拍照上传并进行实名验证
		case R.id.shoot_ID:
			String identityName = identityNameVerify.getText().toString().trim();
			String identityCredentia = identityCredentialVerify.getText().toString().trim();
			String identityIDExpirationTime = identityIDExpirationTimeVerify.getText().toString().trim();
			if (longTime.isChecked()) {
				identityIDExpirationTime = "longTime";
			}
			if (TextUtils.isEmpty(identityName)) {
				showToast("真实姓名不能为空！");
				return;
			} else if (TextUtils.isEmpty(identityCredentia)) {
				showToast("证件号码不能为空！");
				return;
			}
			if (currentType != IDENTITY_QUICK_TYPE) {
				if (TextUtils.isEmpty(identityIDExpirationTime)) {
					showToast("身份证到期时间不能为空！");
					return;
				} else if (!isIDFrontPhotoUpload) {
					showToast("请上传身份证正面照！");
					return;
				} else if (!isIDBackPhotoUpload) {
					showToast("请上传身份证反面照！");
					return;
				}
			}

			if (identityName.length() < 2) {
				showToast("真实姓名不能少于2位！");
				return;
			}
			// if (hasDigit(identityName)) {
			// showToast("真实姓名不能含有数字！");
			// return;
			// }

			if (identityCredentia.length() != 15 && identityCredentia.length() != 18) {
				showToast("证件号输入错误,请重新输入！");
				return;
			}
			new UploadIdentityInfoTask().execute();

			break;
		case R.id.identity_ID_photo_front:
			if (photoDialog == null) {
				photoDialog = new PhotoDialog(IdentityVerifyActivity.this);
			}
			if (photoDialog.isShowing()) {
				photoDialog.dismiss();
			}
			photoDialog.setCaptureFile(mFilePath + mIDFrontFileName);
			photoDialog.show();
			break;
		case R.id.identity_ID_photo_back:
			if (photoDialog == null) {
				photoDialog = new PhotoDialog(IdentityVerifyActivity.this);
			}
			if (photoDialog.isShowing()) {
				photoDialog.dismiss();
			}
			photoDialog.setCaptureFile(mFilePath + mIDBackFileName);
			photoDialog.show();
			break;
		case R.id.tvIdentity:// 认证等级
			CommonAdapter adapter;
			if (isUpdate) {
				adapter = new CommonAdapter(IdentityVerifyActivity.this, Arrays.asList(noneQuickTypes),
						R.layout.item_text_popmenu, ViewHolder.class, mHandleCallBackType);
			} else {
				adapter = new CommonAdapter(IdentityVerifyActivity.this, Arrays.asList(allTypes),
						R.layout.item_text_popmenu, ViewHolder.class, mHandleCallBackType);
			}
			PopupWindow popMenu = AppUtil.getPopupWindow(this, adapter, "请选择认证等级", mTvIdentity,
					new HandlerItemCallBack() {

						@Override
						public void handle(AdapterView<?> parent, View view, int position, long id) {
							String level = mTvIdentity.getText().toString().trim();
							selectLevelType(level);
						}
					});
			// popMenu.setAnimationStyle(R.style.popwindow_anim_style_push);
			popMenu.showAtLocation(mTvIdentity, Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;
		default:
			break;
		}

	}

	@SuppressLint("SimpleDateFormat")
	private void updateIDExpires(int year, int monthOfYear, int dayOfMonth) {
		Calendar time = Calendar.getInstance();
		time.set(year, monthOfYear, dayOfMonth);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		String timeStr = df.format(time.getTime());
		identityIDExpirationTimeVerify.setText(timeStr);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (photoDialog != null) {
			try {
				photoDialog.dismiss();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode != RESULT_OK) {
			return;
		}
		boolean isFront = false;
		if (photoDialog != null) {
			String path = photoDialog.getCaptureFilePath();
			if (!TextUtils.isEmpty(path)) {
				if (path.contains(mIDFrontFileName)) {
					isFront = true;
				} else if (path.contains(mIDBackFileName)) {
					isFront = false;
				} else {
					return;
				}
			} else {
				return;
			}
		} else {
			return;
		}
		if (requestCode == CommonData.PHOTOHRAPH) {
			if (isFront) {
				String sdFrontPath = mFilePath + mIDFrontFileName;
				new UploadAttachmentTask(sdFrontPath, ID_PHOTO_FRONT_PICK).execute();
			} else {
				String sdFrontPath = mFilePath + mIDBackFileName;
				new UploadAttachmentTask(sdFrontPath, ID_PHOTO_BACK_PICK).execute();
			}
		} else if (requestCode == CommonData.PHOTOZOOM) {
			String sdPath = null;
			Cursor cursor = null;
			try {
				Uri picUri = intent.getData();// 获得图片的uri=content://media/external/images/media/75920

				String[] proj = { MediaColumns.DATA };
				cursor = managedQuery(picUri, proj, null, null, null);
				int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
				cursor.moveToFirst();
				sdPath = cursor.getString(column_index); // /storage/sdcard1/Images/照相摄像/新思路装饰2014辅材表.jpg
				sdPath = EncodingUtils.getString(sdPath.getBytes(), "utf-8");
				// 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
				if (Integer.parseInt(Build.VERSION.SDK) < 14) {
					cursor.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
				if (cursor != null) {
					// 4.0以上的版本会自动关闭 (4.0--14;; 4.0.3--15)
					if (Integer.parseInt(Build.VERSION.SDK) < 14) {
						cursor.close();
					}
				}
			}
			if (!TextUtils.isEmpty(sdPath)) {
				if (isFront) {
					new UploadAttachmentTask(sdPath, ID_PHOTO_FRONT_PICK).execute();
				} else {
					new UploadAttachmentTask(sdPath, ID_PHOTO_BACK_PICK).execute();
				}
			}
		}
	}

	// 上传附件
	class UploadAttachmentTask extends AsyncTask<Void, Void, String> {

		private String filePath;
		private int type;
		private ImageUploadDataClass dc = new ImageUploadDataClass();

		public UploadAttachmentTask(String filePath, int type) {
			super();
			this.filePath = filePath;
			this.type = type;
		}

		@Override
		protected void onPreExecute() {
			showProgressDialog();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {
			// 把图片压缩存储到包路径下面
			String name = "temp_" + System.currentTimeMillis() + ".jpg";
			filePath = ImageUtils.bitmap2File(filePath, name, new ImageLoader().getFilePath());

			RequestObject reqObj = new RequestObject();
			reqObj.method = "imagesUpload";
			return uploadFileAndGetErrorMsg(reqObj, filePath, dc);
		}

		@Override
		protected void onPostExecute(String result) {

			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				switch (type) {
				case ID_PHOTO_FRONT_PICK:
					if (!TextUtils.isEmpty(dc.serverPath)) {
						frontImageServerPath = dc.serverPath;
						PicLoad.getImage(photoIDFront, "", filePath);
						isIDFrontPhotoUpload = true;
					}
					break;
				case ID_PHOTO_BACK_PICK:
					if (!TextUtils.isEmpty(dc.serverPath)) {
						backImageServerPath = dc.serverPath;
						PicLoad.getImage(photoIDBack, "", filePath);
						isIDBackPhotoUpload = true;
					}
					break;
				}
			}
			dismissProgressDialog();
		}
	}

	class UploadIdentityInfoTask extends AsyncTask<Void, Void, String> {

		private EasyDataClass dc = new EasyDataClass();

		@Override
		protected void onPreExecute() {
			showProgressDialog();
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Void... params) {

			String identityName = identityNameVerify.getText().toString().trim();
			try {
				identityName = URLEncoder.encode(identityName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			String identityCredentia = identityCredentialVerify.getText().toString().trim();
			String identityIDExpirationTime = identityIDExpirationTimeVerify.getText().toString().trim();
			if (longTime.isChecked()) {
				identityIDExpirationTime = "longTime";
			}

			// 把图片压缩存储到包路径下面
			RequestObject reqObj = new RequestObject();
			if (currentType == IDENTITY_QUICK_TYPE) {
				reqObj.method = "quickCertify";
				reqObj.map.put("realName", identityName);
				reqObj.map.put("certNo", identityCredentia);
				reqObj.map.put("token", token);
			} else {
				reqObj.method = "realNameAuthentication";
				reqObj.map.put("regionType", "DL");
				reqObj.map.put("realName", identityName);
				reqObj.map.put("certNo", identityCredentia);
				reqObj.map.put("token", token);
				reqObj.map.put("businessPeriod", identityIDExpirationTime);
				reqObj.map.put("certFrontPath", frontImageServerPath);
				reqObj.map.put("certBackPath", backImageServerPath);
			}
			return requestDataAndGetErrorMsg(reqObj, dc);
		}

		@Override
		protected void onPostExecute(String result) {
			dismissProgressDialog();
			if (!TextUtils.isEmpty(result)) {
				showToast(result);
			} else {
				setResult(RESULT_OK);
				showToast("信息已提交");
				finish();
			}
		}
	}

	public static class ViewHolder {
		TextView tvBankName;

	}

	private HandleCallBack mHandleCallBackType = new HandleCallBack() {

		@Override
		public void handle(int position, View convertView, ViewGroup parent, Object holder, Object item) {
			// TODO Auto-generated method stub
			final String info = (String) item;
			final ViewHolder h = (ViewHolder) holder;
			AppUtil.setViewText(h.tvBankName, info);
		}
	};

	private void selectLevelType(String level) {
		if (!TextUtils.isEmpty(level)) {
			if (level.equals(quickType)) {
				currentType = IDENTITY_QUICK_TYPE;
				normalContainer.setVisibility(View.GONE);
				identityTip.setText(R.string.identity_quick_tip);
			} else if (level.equals(normalType)) {
				currentType = IDENTITY_NORMAL;
				normalContainer.setVisibility(View.VISIBLE);
				identityTip.setText(R.string.identity_normal_tip);
				identityIDPhotoFrontTip.setText(getString(R.string.identity_ID_photo_front));
			} else {
				currentType = IDENTITY_HOLDING;
				normalContainer.setVisibility(View.VISIBLE);
				identityTip.setText(R.string.identity_hold_tip);
				identityIDPhotoFrontTip.setText(getString(R.string.identity_ID_hold_photo_front));
			}
		}
	}

	public boolean hasDigit(String content) {

		boolean flag = false;

		Pattern p = Pattern.compile(".*\\d+.*");

		Matcher m = p.matcher(content);

		if (m.matches())

			flag = true;

		return flag;

	}
}
